//
//  ImageBgView.m
//  Dayou
//
//  Created by mac on 2018/8/1.
//  Copyright © 2018年 YangYang. All rights reserved.
//

#import "ImageBgView.h"
#import "UIImageOperationView.h"

@interface ImageBgView()
{
    CGFloat currentWidth;
    NSMutableArray *photoArr;
}



@end


@implementation ImageBgView
-(id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor grayColor];
        
    }
    return self;
}

-(void)setWidth:(CGFloat)width
{
    _width = width;
    currentWidth = width;
}

-(void)setImageArr:(NSArray *)imageArr
{
    _imageArr = imageArr;
    photoArr = [NSMutableArray arrayWithArray:imageArr];
}

-(void)refreshUI
{
    for (UIView *view in [self subviews]) {
        [view removeFromSuperview];
    }
    
    UIView *lastView;
    
    if (photoArr.count > 0) {
        for (NSInteger i = 0; i < photoArr.count; ++i) {
            UIImageOperationView *imageView = [[UIImageOperationView alloc] init];
            imageView.image = photoArr[i];
            imageView.tag = i;
            [self addSubview:imageView];
            [imageView makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.left).offset(0 + ((i % 4) * self->currentWidth));
                make.top.equalTo(self.top).offset(0 + ((i / 4) * self->currentWidth));
                make.width.equalTo(self->currentWidth);
                make.height.equalTo(self->currentWidth);
            }];
            lastView = imageView;
            
            __weak typeof(self) weakSelf = self;
            imageView.block = ^{
                NSLog(@"block回调   %ld",imageView.tag);
                [photoArr removeObjectAtIndex:imageView.tag];
                [weakSelf refreshUI];
                if (weakSelf.imageViewBlock) {
                    NSArray *temparr = [NSArray arrayWithArray:photoArr];
                    weakSelf.imageViewBlock(temparr);
                }
            };
            
        }
    }
    
    if (lastView) {
        [self updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(lastView.mas_bottom).offset(0);
        }];
    }
    
}

-(void)setImageViewBlock:(imageBgViewImageArr)imageViewBlock
{
    _imageViewBlock = imageViewBlock;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
